from django.shortcuts import render, get_object_or_404, redirect, HttpResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.models import User
from polls.models import Imgs


# 登录
def login_fu(request):
    print(request)
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    referer = request.META.get('HTTP_REFERER')
    user = authenticate(request, username=username, password=password)
    # 如果用户没有找到
    if user is not None:
        login(request, user)
        return redirect(referer)
    else:
        return HttpResponse("账号和密码有错")


# 注册
def sign_in(request):
    pass


# 登出
def logout(request):
    auth_logout(request)
    referer = request.META.get('HTTP_REFERER')
    print(referer)
    return redirect(referer)


# 跳转到新建文章页面
def go_new_article(request):
    print(request)
    return render(request, 'new_article.html')


# 新建文章
def new_article(request):
    print(request)
    if request.method == 'POST':
        imgs = Imgs()
        title = request.POST.get('title', '')
        img_title = request.POST.get('img_title', '')
        content = request.POST.get('editordata','')
        img_content = request.POST.get('img_content', '')
        img_url = request.FILES.get('img_url')
        imgs.content = content
        imgs.title = title
        imgs.img_title = img_title
        imgs.img_content = img_content
        imgs.img_url = img_url
        imgs.save()
        polls_all_list = Imgs.objects.all()
        return redirect('http://127.0.0.1:8000/polls', {"polls_all_list": polls_all_list})
    else:
        return render(request, {'message': '用户名与密码错误'})


def user_info(request):
    return render(request, 'user_info.html')


# 跳转到注册页面
def to_register(request):
    return render(request, 'register.html')


def register(request):
    print(request)
    if request.method == 'POST':
        username = request.POST.get('user-name', '')
        password = request.POST.get('password', '')
        email = request.POST.get('email', '')
        if(User.objects.filter(username=username).get().usernamereturn):
            pass
        else:
            user = User.objects.create_user(username=username, password=password, email=email)
            user.save()
    polls_all_list = Imgs.objects.all()
    return redirect('http://127.0.0.1:8000/polls', {"polls_all_list": polls_all_list})




